﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;

namespace Lemonc.Tools
{
    class HttpFilesOperter
    {

        //http://localhost:2047/File
        private static string rootUrl;

        public  HttpFilesOperter(string _rootUrl)
        {
            rootUrl = _rootUrl;
        }
        public List<string> GetFiles(string searchPattern)
        {
            string URL = rootUrl + "/GetFiles?searchPattern=" + searchPattern;
            List<string> ret = new List<string>();
            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(URL);
                webRequest.Method = "GET";
                webRequest.Timeout = 5000;
                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                string responseContent;
                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }

                httpWebResponse.Close();
                webRequest.Abort();
                JArray json = JArray.Parse(responseContent);

                foreach (var jObect in json)
                {
                    ret.Add(jObect.ToString().TrimStart('\"').TrimEnd('\"'));
                }
                return ret;

            }
            catch (Exception ex)
            {
                throw;
            }

        }
       
        public void DownFile(string savePath,string fileName,string isDelete)
        {
            string URL = rootUrl + "/DownloadFile?filename=" + fileName + "&isDelete=" + isDelete;
            System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
            string filename = myrp.Headers["Content-Disposition"].Replace("attachment; filename=", "");
            System.IO.Stream so = new System.IO.FileStream(Path.Combine(savePath, filename + ".temp"), System.IO.FileMode.Create);
            FileInfo fi = new FileInfo(Path.Combine(savePath, filename + ".temp"));
            try
            {
                long totalBytes = myrp.ContentLength;

                System.IO.Stream st = myrp.GetResponseStream();


                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                if (File.Exists(fi.FullName.Replace(".temp", "")))
                {
                    File.Delete(fi.FullName.Replace(".temp", ""));
                }
                fi.MoveTo(fi.FullName.Replace(".temp", ""));
            }
            catch (System.Exception ex)
            {
                fi.Delete();
                throw;
            }
        }
        public void UpFile(FileInfo file)
        {
            try
            {
                file.MoveTo(file.FullName + ".temp");
                string URL = rootUrl + "/UploadFile";
                // 边界符
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                //var fileStream =File.OpenRead(filePath);
                //if (File.Exists(file.FullName))
                //{
                //    File.Delete(file.FullName);
                //}
                var fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
                // 最后的结束符
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

                // 文件参数头
                const string filePartHeader =
                    "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                     "Content-Type: application/octet-stream\r\n\r\n";
                var fileHeader = string.Format(filePartHeader, "file", file.Name);
                var fileHeaderBytes = Encoding.UTF8.GetBytes(fileHeader);

                // 开始拼数据
                var memStream = new MemoryStream();
                memStream.Write(beginBoundary, 0, beginBoundary.Length);

                // 文件数据
                memStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
                var buffer = new byte[1024];
                int bytesRead; // =0
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();

                // Key-Value数据
                var stringKeyHeader = "\r\n--" + boundary +
                                       "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                       "\r\n\r\n{1}\r\n";

                Dictionary<string, string> stringDict = new Dictionary<string, string>();
                stringDict.Add("len", "500");
                stringDict.Add("wid", "300");
                foreach (byte[] formitembytes in from string key in stringDict.Keys
                                                 select string.Format(stringKeyHeader, key, stringDict[key])
                                                     into formitem
                                                     select Encoding.UTF8.GetBytes(formitem))
                {
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }

                // 写入最后的结束边界符
                memStream.Write(endBoundary, 0, endBoundary.Length);

                //倒腾到tempBuffer?
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                // 创建webRequest并设置属性
                var webRequest = (HttpWebRequest)WebRequest.Create(URL);
                webRequest.Method = "POST";
                webRequest.Timeout = 100000;
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webRequest.ContentLength = tempBuffer.Length;

                var requestStream = webRequest.GetRequestStream();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                string responseContent;
                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }

                httpWebResponse.Close();
                webRequest.Abort();
                
            }
            catch
            {
                file.MoveTo(file.FullName.Replace(".temp",""));
                throw;
            }

        }

    }
}
